<template>
  <div class="login">
    <el-form
      :model="userinfo"
      :rules="rules"
      label-width="100px"
      class="loginInfo"
      ref="loginInfo"
    >
      <el-form-item prop="username" label="用户名">
        <el-input v-model="userinfo.username" clearable></el-input>
      </el-form-item>
      <el-form-item prop="password" label="密码" >
        <el-input v-model="userinfo.password" show-password clearable></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="login">登录</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
//引入封装的登录接口
import { userLogin } from "../request/api";
import {mapActions} from 'vuex'
export default {
  data() {
    return {
      //输入项
      userinfo: {
        username: "",
        password: "",
      },
      //验证规则
      rules: {
        username: [
          { required: true, message: "请输入用户名称", trigger: "blur" },
          {
            min: 2,
            max: 15,
            message: "长度在 2 到 15 个字符",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 6,
            max: 16,
            message: "长度在 2 到 16 个字符",
            trigger: "blur",
          },
        ],
      },
    };
  },
  methods: {
    ...mapActions(['changeUser']),
    //封装一个登录事件
    login() {
      //console.log(this.userinfo, "表单对象");
      this.$refs.loginInfo.validate((val) => {
        if (val) {
          // console.log(this.userinfo, "表单对象");

          userLogin(this.userinfo).then((res) => {
            if (res.code == 200) {
              console.log(res, "登录响应");
              this.$message.success(res.msg);
              /*
                // //把登陆结果存储到本地存储中
                // sessionStorage.setItem("userinfo", JSON.stringify(res.  list)   
                  );
              */
              // 把登陆结果存储到vuex中
              this.changeUser(res.list)
              //验证成功跳转到index界面
              this.$router.push('/index')
            } else {
              this.$message.error(res.msg);
            }
          });
        } else {
          console.log("验证失败");
        }
      });
    },
  },
};
</script>

<style scoped>
.login {
  width: 100%;
  height: 100vh;
  background: #ccc;
}
.loginInfo {
  width: 400px;
  height: 300px;
  position: absolute;
  left: 35%;
  top: 35%;
}
</style>